import util from './util.js'

// let baseUrl = '/baseUrl' //h5跨域用'
let baseUrl = 'http://hanbang.diruankeji.com/api' //线上用'//'
let newBaseUrl = 'http://hanbang.diruankeji.com'

/**
 * 请求头
 * @param {string} url 请求的链接
 * @param {Object} params 参数 {key : value, ...}
 * @param {string} method 判断是否需要token，或者请求为psot或get  
 */

let intercept = false;//token过期之后判断重复请求
const sendrequest = (url,params,method = {}) =>{

	let token = '';
	
	if(method.tokenJudge && !uni.getStorageSync('token')){
		uni.showToast({title:'请先登录',icon:'none'})
		setTimeout(()=>{
			util.redirectTo('/pages/login/login',{},'redirectTo')
		},1000)
		return new Promise(resolve=>{resolve('该接口需要登录')});
	}
	
	if(uni.getStorageSync('token')) token = uni.getStorageSync('token');

	return new Promise((resolve,reject)=>{
		uni.request({
			url:baseUrl + url,
			method:method.type || 'POST',
			header: {
				'content-type': 'application/x-www-form-urlencoded;application/json',
				'token':token
			},
			dataType:'json',
			data:params,
			success:res=>{
				if(res && res.data.code == 401) {//token过期
					if(intercept) return false;
					intercept = true;
					if(uni.getStorageSync('token')){
						uni.showToast({title:'已过期，请重新登录',icon:'none'})
						uni.request({
							url:baseUrl + '/login/logOut',
							method:'POST',
							header: {
								'content-type': 'application/x-www-form-urlencoded;application/json',
								'token':token
							},
							dataType:'json',
							success:(v)=>{
								uni.clearStorageSync();
								intercept = false;
								setTimeout(()=>{
									util.redirectTo('/pages/login/login',{},'redirectTo')
								},1000)
							}
						})
						
					}else {
						setTimeout(()=>{
							util.redirectTo('/pages/login/login',{},'redirectTo')
						},1000)
					}
					

				}else resolve(res.data)
			},
			fail:err=>{
				setTimeout(()=>{
					util.redirectTo('/',{},'switchTab')
				},1000)
			}
		})
	})
}
export default {
	sendrequest,baseUrl,newBaseUrl
}